<?php
/**
 * Class UserController created by Pixoid.
 *
 * @version 1.0
 */
class UserController extends Controller {

    public function actions() {
        return array('captcha' => array('class' => 'CCaptchaAction', 'transparent' => true));
    }

    function filters() {
        return array('accessControl', array('ESetReturnUrlFilter + list, view, setemail'),);
    }

    public function accessRules() {
        return array(array('allow', 'actions' => array('captcha', 'autocomplete', 'list', 'login', 'view', 'registration', 'recover', 'activate'), 'users' => array("*"),), array('allow', 'actions' => array('setemail', 'logout', 'settings', 'addRating', 'removeRating', 'FilterDelete'), 'users' => array("@"),), array('allow', 'actions' => array('ban', 'active', 'setRole'), 'expression' => 'Y::user()->isAdmin()',), array('deny', 'users' => array('*')));
    }

    public function actionAutocomplete($term) {
        if(Yii::app()->request->isAjaxRequest && !empty($term)) {
            $variants = array();
            $criteria = new CDbCriteria;
            $criteria->select = 'name';
            $criteria->addSearchCondition('name', $term . '%', false);
            $tags = Tags::model()->findAll($criteria);
            if(!empty($tags)) {
                foreach($tags as $tag) {
                    $variants[] = $tag->attributes['name'];
                }
            }
            echo CJSON::encode($variants);
        } else
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    public function actionSetRole() {
        $user = $this->loadUser($_GET['id']);
        $role = $_GET['role'];
        if(in_array($role, array(User::ROLE_ADMIN, User::ROLE_USER, User::ROLE_MODERATOR))) {
            $user->role = $role;
            $user->save();
        }
        Y::goBack();
    }

    public function actionBan() {
        $user = $this->loadUser($_GET['id']);
        if($user->role == User::ROLE_USER) {
            $whot = isset($_POST['whot']) ? $_POST['whot'] : "Без причины";
            $this->sendMail($user->email, '../email/ban', array('model' => $user, "whot" => $whot), 'Ваш аккаунт был заблокирован.');
            $user->status = User::STATUS_BANNED;
            $user->save();
        }
        Y::goBack();
    }

    public function actionActive() {
        $user = $this->loadUser($_GET['id']);
        if($user->role == User::ROLE_USER) {
            $this->sendMail($user->email, '../email/active', array('model' => $user), 'Ваш аккаунт был активирован.');
            $user->status = User::STATUS_ACTIVE;
            $user->save();
        }
        Y::goBack();
    }

    public function actionList() {
        $this->keyWord = "пользователи, люди, просители, помошники";
        $this->description = "Отряд людей, которые зарегистрированы на нашем портале";
        $this->pageTitle = 'Список пользователей';

        $criteria = new CDbCriteria();
        $criteria->with = array("service", "suggest");
        if(isset($_GET['search'])) {
            $criteria->addSearchCondition('username', $_GET['search'], true, "OR");
        }
        $this->breadcrumbs = array("name" => "Пользователи");
        $sort = new CSort();
        $sort->sortVar = 'sort';
        $sort->defaultOrder = 't.t_create DESC';
        $sort->multiSort = true;
        $sort->attributes = array(
            't_create' => array(
                'asc' => 't.t_create ASC',
                'desc' => 't.t_create DESC',
                'default' => 'desc',
                'label' => 'дате',
            ),
            'status' => array(
                'asc' => 't.status ASC',
                'desc' => 't.status DESC',
                'default' => 'desc',
                'label' => 'статусу',
            ),
            'rating' => array(
                'asc' => 't.rating ASC',
                'desc' => 't.rating DESC',
                'default' => 'desc',
                'label' => 'рейтингу',
            ),
        );
        $dependency = new CDbCacheDependency('SELECT MAX(t_create) FROM User');
        $users = new EActiveDataProviderEx( 'User', array(
                'criteria' => $criteria,
                'sort' => $sort,
                'pagination' => array(
                    'pageSize' => Y::param("countInPage")
                ),
                'cache'=>array(360, $dependency)
            )
        );
        $this->render('list', compact('users'));
    }

    public function actionAddRating() {
        $type = $_GET['type'];
        $user = false;
        if($type == Rating::TYPE_USER) {
            $item = User::model()->findByPk($_GET['id']);
        } elseif($type == Rating::TYPE_COMMENT) {
            $item = Comment::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        } elseif($type == Rating::TYPE_SERVICE) {
            $item = Service::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        } elseif($type == Rating::TYPE_SUGGEST) {
            $item = Suggest::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        }
        if(!$item) {
            return false;
        }
        if(!Rating::model()->exists("user_id = ? AND item_id = ? AND type = ?", array(Y::userId(), $item->id, $type))) {
            Rating::addNew($item->id, $type);
            $item->rating = $item->rating + 1;
            if($user) {
                $user->rating = $user->rating + 1;
                $user->save();
            }
            $item->save();
        }
        return $this->widget("UserRating", array("item_id" => $item->id, "type" => $type, 'rating' => $item->rating, 'is_down' => false));
    }

    public function actionRemoveRating() {
        $type = $_GET['type'];
        $user = false;
        if($type == Rating::TYPE_USER) {
            $item = User::model()->findByPk($_GET['id']);
        } elseif($type == Rating::TYPE_COMMENT) {
            $item = Comment::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        } elseif($type == Rating::TYPE_SERVICE) {
            $item = Service::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        } elseif($type == Rating::TYPE_SUGGEST) {
            $item = Suggest::model()->findByPk($_GET['id']);
            $user = User::model()->findByPk($item->owner_id);
        }
        if(!$item) {
            return false;
        }
        if(!Rating::model()->exists("user_id = ? AND item_id = ? AND type = ?", array(Y::userId(), $item->id, $type))) {
            Rating::addNew($item->id, $type);
            $item->rating = $item->rating - 1;
            if($user) {
                $user->rating = $user->rating - 1;
                $user->save();
            }
            $item->save();
        }
        return $this->widget("UserRating", array("item_id" => $item->id, "type" => $type, 'rating' => $item->rating, 'is_down' => false));
    }

    public function actionSettings() {

        $this->keyWord = "настройки, сетинги, смена пароля, смена личных данных";
        $this->description = "Настройки профиля пользователя";
        $this->pageTitle = 'Настройки';

        $user = $this->loadUser(Y::userId());
        $lowername = strtolower($user->username);
        $this->breadcrumbs = array("name" => "<a href='/user/{$user->id}'>{$user->username}</a>", "name2" => "Настройки");
        $FormSettings = FormSettings::model()->findByPk($user->id);
        $form = new CForm($FormSettings->config, $FormSettings);
        if($form->submitted('sand') && $form->validate()) {
            $FormSettings->save(false);
            Yii::app()->user->setFlash("success-block", 'Настройки успешно изменены.');
            $this->redirect("/user/" . $user->id);
        }
        $FormPassword = FormChangePassword::model()->findByPk($user->id);
        $form2 = new CForm($FormPassword->config, $FormPassword);
        if($form2->submitted('send_new_password')) {
            if($form2->validate()) {
                $FormPassword->password = User::encrypt($FormPassword->password);
                $FormPassword->save(false);
                Yii::app()->user->setFlash("success-block", 'Пароль успешно изменен.');
                $this->redirect("/user/" . $user->id);
            }
        }
        $this->render("settings", compact('user', 'form', 'form2'));
    }

    public function actionView() {
        $user = $this->loadUser($_GET['id']);
        $this->breadcrumbs = array("name" => "{$user->username}");
        if($user->status == User::STATUS_BANNED && !Y::user()->isAdmin()) {
            $this->render("user_baned", compact("user"));
            return true;
        }
        $criteria = new CDbCriteria();
        $criteria->condition = "t.owner_id = :user_id";
        $criteria->params = array(":user_id" => $user->id);
        $criteria->order = "t.t_create DESC";
        $criteria->with = "owner";
        $services = new CActiveDataProvider('Service', array('criteria' => $criteria, 'pagination' => array('pageSize' => Y::param("countInPage"),),));
        $suggests = new CActiveDataProvider('Suggest', array('criteria' => $criteria, 'pagination' => array('pageSize' => Y::param("countInPage"),),));
        $filters = array();
        $form = '';
        if(Y::isAuthed() && $user->id == Y::userId()) {
            $criteria = new CDbCriteria();
            $criteria->condition = "t.owner_id = :user_id";
            $criteria->params = array(":user_id" => $user->id);
            $criteria->limit = 3;
            $filters = new CActiveDataProvider('UserFilter', array('criteria' => $criteria));
            if(count($filters->data) < 3) {
                $FormUserFilter = new FormUserFilter();
                $form = new CForm($FormUserFilter->config, $FormUserFilter);
                if($form->submitted('send') && $form->validate()) {
                    Yii::app()->user->setFlash("success-block", 'Фильтр успешно добавлен.');
                    $this->redirect("/user/" . $user->id . "#tab4");
                }
            }
        }

        $this->keyWord = "пользователь, " . $user->username;
        $this->description = "Профиль пользователя - " . $user->username;
        $this->pageTitle = "Профиль пользователя - " . $user->username;

        $this->render("view", compact('user', 'services', 'suggests', 'filters', 'form'));
    }

    public function actionFilterDelete() {
        $filter = UserFilter::model()->findByPk($_GET['id']);
        if(!$filter) {
            throw new CHttpException(404);
        }
        if($filter->owner_id != Y::userId()) {
            throw new CHttpException(403);
        }
        $user = User::model()->findByPk($filter->owner_id);
        $filter->delete();
        Yii::app()->user->setFlash("success-block", 'Фильтр успешно удален.');
        $this->redirect("/user/" . $user->id . "#tab4");
    }

    public function actionLogin() {

        $this->pageTitle = 'Вход';
        $this->keyWord = "Вход, login, авторизация";
        $this->description = "Вход только для пользователей";

        $service = Yii::app()->request->getQuery('service');
        if(isset($service)) {
            $authIdentity = Yii::app()->eauth->getIdentity($service);
            $authIdentity->redirectUrl = "/";
            $authIdentity->cancelUrl = $this->createAbsoluteUrl('user/login');
            if($authIdentity->authenticate()) {
                $identity = new ServiceUserIdentity($authIdentity);
                // Успешный вход
                if($identity->authenticate()) {
                    Yii::app()->user->login($identity);
                    $authIdentity->redirect();
                } else {
                    $authIdentity->cancel();


                }
            }
            $this->redirect(array('user/login'));
        }
        $this->render('login');
    }

    public function actionLogout() {
        Yii::app()->user->logout();
        $this->redirect("/");
    }

    public function actionRegistration() {

        $this->keyWord = "Регистрация, signup";
        $this->description = "Регистрация пользователей в системе";
        $this->pageTitle = 'Регистрация';

        $FormRegistration = new FormRegistration();
        $form = new CForm($FormRegistration->config, $FormRegistration);
        if($form->submitted('registration') && $form->validate()) {
            Yii::app()->user->setFlash("success-block", 'Регистрация прошла успешно, проверьте свой E-Mail.');
            $this->redirect("/login");
        }
        $this->render('registration', array('form' => $form));
    }

    public function actionRecover() {

        $this->keyWord = "Вспомнить,пароль,забыли пароль";
        $this->description = "Вспомнить пароль, если забыли";
        $this->pageTitle = 'Вспомнить пароль';

        if(isset($_GET['key']) && !empty($_GET['key'])) {

            $user = FromRecoverPassword::model()->find('code = :key', array(":key" => $_GET['key']));
            if(!$user) {
                Yii::app()->user->setFlash("error", 'Что случилось? Возможно, вы перешли не по той ссылке.');
                $this->redirect("/");
            }
            $form = new CForm($user->config, $user);
            if($form->submitted('restore') && $form->validate()) {
                Yii::app()->user->setFlash("success-block", 'Проверьте свой E-Mail. Там небольшая инструкция.');
                $this->redirect("/login");
            }
            $this->render('recoverPassword', array("form" => $form));
        }
        if(empty($_GET['key'])) {
            $FormRecover = new FormRecover();
            $form = new CForm($FormRecover->config, $FormRecover);
            if($form->submitted('recover') && $form->validate()) {
                Yii::app()->user->setFlash("success-block", 'Проверьте свой E-Mail. Там небольшая инструкция.');
                $this->redirect("/");
            }
            $this->render('recover', array("form" => $form));
        }
    }

    public function actionSetemail() {
        if(Y::isAuthed()) {
            $user = User::model()->findByPk(Y::userId());
            $ne = substr(md5($user->service_name . $user->identity), 0, 12);
            if($user->email != $ne . "@example.com") {
                $this->redirect("/");
            }
            $FormSetEmail = new FormSetEmail();
            $form = new CForm($FormSetEmail->config, $FormSetEmail);
            if($form->submitted('send') && $form->validate()) {
                Yii::app()->user->setFlash("success-block", 'Спасибо за доверие!');
                $this->redirect("/");
            }
            $this->render("setemail", compact('form'));
        } else {
            throw new CHttpException(404);
        }
    }

    public function actionActivate() {

        $this->keyWord = "Аактивация, пользователя";
        $this->description = "Вот так мы активизируем пользователей";
        $this->pageTitle = 'Активировать аккаунт';

        $user = User::model()->find('code = :key', array(":key" => $_GET['key']));
        if(!$user) {
            Yii::app()->user->setFlash("error", 'Неправильный код активации');
            $this->redirect("/");
        } else {
            $user->code = '';
            $user->status = User::STATUS_ACTIVE;
            $user->save();
            Yii::app()->user->setFlash("success-block", 'Ваш аккаунт активирован.');
            $this->redirect("/login");
        }

    }
}
